package izzat.fit.dbservice.service;

import izzat.fit.dbservice.base.entity.BaseEntity;
import izzat.fit.dbservice.base.service.BaseService;
import izzat.fit.dbservice.entity.RequestEntity;
import izzat.fit.dbservice.entity.mine.HistoricalStatistics;
import izzat.fit.dbservice.entity.mine.Record;
import izzat.fit.dbservice.entity.mine.Schedule;
import izzat.fit.dbservice.entity.mine.User;
import izzat.fit.dbservice.mapper.MineMapper;
import izzat.fit.dbservice.mapper.TrainingMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @ClassName: MineService
 * @Description:
 * @Author: Izzat
 * @Date: 2019-12-29 18:26
 * @Version: v1.0
 */
@Service
public class MineService implements BaseService {
    @Autowired
    private MineMapper mineMapper;
    @Autowired
    private TrainingMapper trainingMapper;

    public List<User> getAllUser(){
        return mineMapper.getAllUser();
    }

    public List<Schedule> getScheduleByUserId(int userId){
        List<Schedule> data =  getPlanName(mineMapper.getScheduleByUserId(userId));
        return Optional.ofNullable(data).orElse(new ArrayList<>());
    }

    private List<Schedule> getPlanName(List<Schedule> list){
        for (int i = 0; i < list.size(); i++){
            if(list.get(i).getPlan() == -1){
                list.get(i).setPlanName("休息日");
            }
            else
            list.get(i).setPlanName(trainingMapper.findPlanById(list.get(i).getPlan()).getName());
        }
        return list;
    }

    public int updatePlanByUserAndDate(Schedule schedule){
        return mineMapper.updatePlanByUserAndDate(
                schedule.getPlan(),
                schedule.getUserid(),
                schedule.getDate());
    }

    public int addRecord(Record record){
        return mineMapper.addRecord(record);
    }

    public HistoricalStatistics findRecordByUserAndRange(RequestEntity request){
        List<Record> list = mineMapper.findRecordByUserAndRange(request.getId(),request.getStartTime(),request.getEndTime());
        HistoricalStatistics result = new HistoricalStatistics();
        int times = list.size();
        int minues  = 0;
        int days = 1;
        for(int i = 0; i < list.size(); i++){
            String tmp = list.get(i).getData() + "";
            String finalData = tmp.substring(0,4) + "/" + tmp.substring(4,6) + "/" + tmp.substring(6,8);
            list.get(i).setDatas(finalData);
            minues = minues + list.get(i).getDuration();
            if(i > 0 && list.get(i-1).getData() != list.get(i).getData())
                days++;
        }
        return result.list(list).cumulativeDays(days).CumulativeMinutes(minues).cumulativeTimes(times);
    }

    @Override
    public Object findById(Integer integer) {
        return null;
    }
}
